package com.example.algorithm.dualpointer;

import com.example.algorithm.datastructure.ListNode;

/**
 * 删除链表中倒数第 n 个节点
 */
public class RemoveLastNNode {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.setNext(head);

        ListNode fast = dummy;
        ListNode slow = dummy;

        // 快指针先向前移动n+1步
        for (int i = 0; i < n + 1; i++) {
            fast = fast.getNext();
        }

        // 快慢指针同时向前移动，直到快指针到达链表末尾
        while (fast != null) {
            fast = fast.getNext();
            slow = slow.getNext();
        }

        // 删除倒数第n个节点
        slow.setNext(slow.getNext().getNext());

        return dummy.getNext();
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1)
                .setNext(new ListNode(2)
                        .setNext(new ListNode(3)
                                .setNext(new ListNode(4)
                                        .setNext(new ListNode(5)
                                        )
                                )
                        )
                );

        ListNode newHead = new RemoveLastNNode().removeNthFromEnd(listNode, 2);
        System.out.println(newHead);
    }
}